<?php
class Executor {
	private $cmd;
	private $extra;
	
	private $pipes;
	private $descriptor;
	
	private $exitcode;
	
	private $process;
	
	private $status;
	
	public function __construct($cmd = '') {
		$this->cmd = $cmd;
		$this->descriptor = array(
			0 => array('pipe', 'r'),
			1 => array('pipe', 'w'),
			2 => array('pipe', 'w')
		);
	}
	
	public function setRedirectErrorToOut($status) {
		$this->extra = $status ? ' 2>&1' : '';
	}
	
	public function execute() {
		$this->process = proc_open($this->cmd . $this->extra, $this->descriptor, $this->pipes);
	}
	
	public function join() {
		foreach ($this->descriptor as $key=>$p) {
			if ($p[0] == 'pipe') {
				fclose($this->pipes[$key]);
			}
		}
		
		$this->exitcode = proc_close($this->process);
	}
	
	public function getExitCode() {
		return $this->exitcode;
	}
	
	public function getInputStream() {
		return $this->pipes[0];
	}
	
	public function getOutputStream() {
		return $this->pipes[1];
	}
	
	public function getErrorStream() {
		return $this->pipes[2];
	}
}

